package com.yufan.frame.shardingsphere;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * mysql数据源
 */
@Configuration
@MapperScan(basePackages = ShardingMysqlConfig.Package, sqlSessionFactoryRef = ShardingMysqlConfig.sessionFactoryName)
public class ShardingMysqlConfig {

    // --------------------------------- customer config -------------------------------
    private static final String dbName = "sharding";//数据源配置后缀
//    private static final String config = "spring.datasource.sharding";
    static final String Package = "com.yufan.dao.sharding";//mapper目录
    private static String mybatisMapperLocations = "";//classpath:mapper/*.xml
    // ---------------------------------------------------------------------------------


    private static final String dataSourceName = dbName + "DataSource";
    private static final String transactionManagerName = dbName + "TransactionManager";
    static final String sessionFactoryName = dbName + "SqlSessionFactory";
    static final String sessionTemplateName = dbName + "SqlSessionTemplate";


//    @Resource(name = dataSourceName)
//    public DataSource dataSource;

    @Resource(name = dataSourceName)
    public DataSource dataSource;


//    @Bean(transactionManager)
//    public DataSourceTransactionManager transactionManager() {
//        return new DataSourceTransactionManager(dataSource());
//    }

    @Bean(sessionFactoryName)
    public SqlSessionFactory sessionFactory(@Qualifier("shardingDataSource") DataSource mysqlDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(mysqlDataSource);
        if (mybatisMapperLocations != null && mybatisMapperLocations.length() > 0) {
            sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mybatisMapperLocations));
        }

        //mybatis config
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);//驼峰
        sessionFactory.setConfiguration(configuration);

        return sessionFactory.getObject();
    }

    @Bean(sessionTemplateName)
    public SqlSessionTemplate sessionTemplate(@Qualifier(sessionFactoryName) SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}